package org.jeecg.modules.compilation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.es.JeecgElasticsearchTemplate;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.compilation.dto.AddNoteDTO;
import org.jeecg.modules.compilation.dto.NoteDTO;
import org.jeecg.modules.compilation.dto.NoteFileDTO;
import org.jeecg.modules.compilation.entity.CiDoc;
import org.jeecg.modules.compilation.entity.CiNote;
import org.jeecg.modules.compilation.dto.NotesDTO;
import org.jeecg.modules.compilation.mapper.CiDocMapper;
import org.jeecg.modules.compilation.mapper.CiNoteMapper;
import org.jeecg.modules.compilation.service.ICiDocService;
import org.jeecg.modules.compilation.service.ICiNoteService;
import org.jeecg.modules.compilation.util.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: ci_note
 * @Author: jeecg-boot
 * @Date:   2024-03-15
 * @Version: V1.0
 */
@Service
public class CiNoteServiceImpl extends ServiceImpl<CiNoteMapper, CiNote> implements ICiNoteService {

    @Autowired
    private CiNoteMapper ciNoteMapper;

    @Autowired
    private CiDocMapper ciDocMapper;
    @Autowired
    private JeecgElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ICiDocService ciDocService;

    @Override
    public List<NotesDTO> getNoteCount(String userId) {
        return ciNoteMapper.selectFileNamesByUserId(userId);
    }

    @Override
    public List<NoteFileDTO> getnote(String ducumentSn) {
        //获取登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();

        return ciNoteMapper.selectFileNameAndCreateTime(userId,ducumentSn);
    }

    @Override
    public Boolean addOrUpdate(CiNote ciNote) {
        //获取登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();

        LambdaQueryWrapper<CiNote> ciNoteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ciNoteLambdaQueryWrapper.eq(CiNote::getUserId,userId)
                .eq(CiNote::getNoteSn,ciNote.getNoteSn());
        CiNote one = this.getOne(ciNoteLambdaQueryWrapper);
        if(one != null) {
            BeanUtils.copyProperties(one, ciNote,"content");
            return this.saveOrUpdate( ciNote );
        }

        QueryWrapper<CiDoc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("document_sn",ciNote.getDocumentSn());
        CiDoc note = ciDocService.getOne(queryWrapper);
        String documentTitle = note.getDocumentTitle();
        ciNote.setNoteSn(CommonUtil.getSn()).setUserId(userId).setDocumentTitle(documentTitle).setEnableFlag(note.getEnableFlag());

        return this.saveOrUpdate( ciNote );
    }

    @Override
    public List<NoteDTO> searchNoteList(String documentTitle) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        SearchRequest request=new SearchRequest("note");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must((QueryBuilders.matchQuery("userId", userId)));
        if (documentTitle != null && !"".equals(documentTitle)) {
            boolQuery.must(QueryBuilders.matchQuery("documentTitle", documentTitle));
        }
//        request.source().query(QueryBuilders.matchAllQuery());
        request.source().query(boolQuery);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<NoteDTO> list = handleResponse(search);
        restHighLevelClient.close();
        return list;
    }

    private List<NoteDTO> handleResponse(SearchResponse search) {
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        System.out.println(value + "条数据");
        System.out.println("-------------------------------------");
        SearchHit[] hits1 = hits.getHits();
        List<NoteDTO> list  = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String josn= hit.getSourceAsString();
            NoteDTO ciFavorite = JSON.parseObject(josn, NoteDTO.class);
            list.add(ciFavorite);
        }
        return list;
    }
}
